package com.ruoyi.record.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.domain.BasicWork;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.basic.mapper.BasicWorkMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.record.domain.RecordSalaryContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.record.mapper.RecordBenefitContentMapper;
import com.ruoyi.record.domain.RecordBenefitContent;
import com.ruoyi.record.service.IRecordBenefitContentService;
import com.ruoyi.common.core.text.Convert;

/**
 * 保险金内容Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-02-19
 */
@Service
public class RecordBenefitContentServiceImpl extends ServiceImpl<RecordBenefitContentMapper, RecordBenefitContent> implements IRecordBenefitContentService
{
    @Autowired
    private BasicUserMapper basicUserMapper;

    @Autowired
    private BasicWorkMapper basicWorkMapper;

    /**
     * 查询保险金内容
     * 
     * @param contentId 保险金内容主键
     * @return 保险金内容
     */
    @Override
    public RecordBenefitContent selectRecordBenefitContentByContentId(Long contentId)
    {
        return baseMapper.selectRecordBenefitContentByContentId(contentId);
    }

    /**
     * 查询保险金内容列表
     * 
     * @param recordBenefitContent 保险金内容
     * @return 保险金内容
     */
    @Override
    public List<RecordBenefitContent> selectRecordBenefitContentList(RecordBenefitContent recordBenefitContent)
    {
        return baseMapper.selectRecordBenefitContentList(recordBenefitContent);
    }

    /**
     * 新增保险金内容
     * 
     * @param recordBenefitContent 保险金内容
     * @return 结果
     */
    @Override
    public int insertRecordBenefitContent(RecordBenefitContent recordBenefitContent)
    {
        recordBenefitContent.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(recordBenefitContent);
    }

    /**
     * 修改保险金内容
     * 
     * @param recordBenefitContent 保险金内容
     * @return 结果
     */
    @Override
    public int updateRecordBenefitContent(RecordBenefitContent recordBenefitContent)
    {
        recordBenefitContent.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(recordBenefitContent);
    }

    /**
     * 批量删除保险金内容
     * 
     * @param contentIds 需要删除的保险金内容主键
     * @return 结果
     */
    @Override
    public int deleteRecordBenefitContentByContentIds(String contentIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(contentIds)));
    }

    /**
     * 删除保险金内容信息
     * 
     * @param contentId 保险金内容主键
     * @return 结果
     */
    @Override
    public int deleteRecordBenefitContentByContentId(Long contentId)
    {
        return baseMapper.deleteById(contentId);
    }

    /**
     * 导入保险金内容
     * @param contentList 员工行政职务列表
     * @param benefitId
     * @param isUpdateSupport
     * @param operName 操作用户
     * @return
     */
    @Override
    public String importContent(List<RecordBenefitContent> contentList, Long benefitId, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(contentList) || contentList.size() == 0)
        {
            throw new ServiceException("导入员工行政职务数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecordBenefitContent content : contentList)
        {
            try
            {
                if(StringUtils.isEmpty(content.getIdCard())){
                    continue;
                }
                content.setBenefitId(benefitId);
                // 获取用户信息
                BasicUser basicUser = basicUserMapper.selectOne(new LambdaQueryWrapper<BasicUser>().eq(BasicUser::getIdCard, content.getIdCard()));
                if(StringUtils.isNull(basicUser)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + content.getUserName() + " 不存在");
                    continue;
                }
                content.setUserId(basicUser.getId());

                RecordBenefitContent info = baseMapper.selectOne(new LambdaQueryWrapper<RecordBenefitContent>()
                        .eq(RecordBenefitContent::getBenefitId, content.getBenefitId())
                        .eq(RecordBenefitContent::getBenefitType, content.getBenefitType())
                        .eq(RecordBenefitContent::getUserId, content.getUserId()));
                if (StringUtils.isNull(info))
                {
                    content.setCreateBy(operName);
                    this.insertRecordBenefitContent(content);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行员工保险金信息导入成功");
                }
                else if (isUpdateSupport)
                {
                    content.setContentId(info.getContentId());
                    content.setUpdateBy(operName);
                    this.updateRecordBenefitContent(content);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行员工保险金信息更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行员工保险金信息已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行员工保险金信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验保险金内容
     * @param recordBenefitContent 保险金内容
     * @return
     */
    @Override
    public boolean checkBenefitContent(RecordBenefitContent recordBenefitContent) {
        Long contentId = StringUtils.isNull(recordBenefitContent.getContentId()) ? -1L : recordBenefitContent.getContentId();
        LambdaQueryWrapper<RecordBenefitContent> queryWrapper = new LambdaQueryWrapper<RecordBenefitContent>().eq(RecordBenefitContent::getBenefitId, recordBenefitContent.getBenefitId());
        if(StringUtils.isNotNull(recordBenefitContent.getUserId())){
            queryWrapper.eq(RecordBenefitContent::getUserId, recordBenefitContent.getUserId());
        }
        RecordBenefitContent info = baseMapper.selectOne(queryWrapper.last("limit 1"));
        if (StringUtils.isNotNull(info) && info.getContentId().longValue() != contentId.longValue())
        {
            return false;
        }
        return true;
    }
}
